package com.golxen.framework.common.server.agent;


import com.golxen.framework.common.BuiltinPlugin;
import com.golxen.framework.common.CommandPlugin;
import com.golxen.framework.common.ShutDownPlugin;
import com.golxen.framework.common.server.eServerType;
import com.golxen.framework.common.server.BaseServer;
import com.golxen.framework.manager.TempMgr;
import com.golxen.framework.netty.session.agent.ServerClientMgr;
import com.golxen.framework.netty.websocket.AgentWebSocketServer;
import com.golxen.utils.LogUtil;
import com.golxen.utils.YmlUtil;

import java.util.List;

public final class AgentServer extends BaseServer {


    private AgentWebSocketServer sslServer;

    private static AgentServer gatewayServer;

    private boolean isStop;

    public boolean isStop() {
        return isStop;
    }

    public void setStop(boolean stop) {
        this.isStop = stop;
    }

    private AgentServer() {

    }

    public static AgentServer getInstance() {
        if (gatewayServer == null) {
            gatewayServer = new AgentServer();
        }

        return gatewayServer;
    }

    @Override
    public List<TempMgr> getMgrList() {
        return null;
    }

    @Override
    public boolean start() {

        setServerType(eServerType.AGENT);

        CommandPlugin.start();

        if (!super.start()) {
            return false;
        }

        if (!AgentPlayerMgr.init()) {
            return false;
        }

        if (!ServerClientMgr.init()) {
            return false;
        }

        if (!startNetty()) {
            return false;
        }

        ShutDownPlugin.registShutDownFn(() -> {
            LogUtil.CONSOLE.info("AgentServer kill 关闭服务器");
            AgentServer.getInstance().newStop();

        });

        return true;
    }

    @Override
    public boolean stop() {
        return this.newStop();
    }

    public boolean newStop() {
        try {
            sslServer.stop();
            AgentPlayerMgr.stop(); //关闭与与客户端的Channel
        } catch (Exception e) {
            LogUtil.CONSOLE.error("AgentServer stop error", e);
            return false;
        } finally {
            LogUtil.CONSOLE.info("AgentServer shutdown over....");
        }

        return true;
    }

    protected boolean startNetty() {

        sslServer = new AgentWebSocketServer(BuiltinPlugin.getServerId(), YmlUtil.getInt("netty.agent.port"));
        try {
            sslServer.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    public static void main() {

        AgentServer agentServer = AgentServer.getInstance();
        if (!agentServer.start()) {
            throw new RuntimeException("AgentServer start up fail");
        }

    }

}
